import cv2


def generate_video(path, face_path, reverse_path, reverse=False):
    """

    :param path: 原视频文件地址
    :param face_path: 人脸部分视频地址
    :param reverse_path: 人脸部分x轴翻转视频地址
    :param reverse: 是否生成人脸部分x轴翻转视频
    :return:
    """
    face_cascade = cv2.CascadeClassifier(
        r'C:\Anaconda3\envs\zy\Lib\site-packages\cv2\data\haarcascade_frontalface_default.xml')
    # eye_cascade = cv2.CascadeClassifier(
    #     r'C:\Anaconda3\envs\zy\Lib\site-packages\cv2\data\haarcascade_eye.xml')
    # w_max = 0
    # h_max = 0
    # 帧率
    fps = 30
    # 图片尺寸
    img_size = (320, 320)
    fourcc = cv2.VideoWriter_fourcc('M', 'J', 'P', 'G')
    face_video_writer = cv2.VideoWriter(face_path, fourcc, fps, img_size)
    if reverse:
        reverse_video_writer = cv2.VideoWriter(reverse_path, fourcc, fps, img_size)
    cap = cv2.VideoCapture(path)
    while True:
        ret, img = cap.read()
        if not ret:
            break
        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        faces = face_cascade.detectMultiScale(gray, 1.1, 5)
        if len(faces) > 0:
            for faceRect in faces:
                x, y, w, h = faceRect
                if w < 100 or h < 100:
                    break
                # cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2)
                # roi_gray = gray[y:y + h // 2, x:x + w]
                # roi_color = img[y:y + h // 2, x:x + w]
                out_frame = cv2.resize(img[y:y + h, x:x + w], (320, 320))
                cv2.imshow("rec", out_frame)
                face_video_writer.write(out_frame)
                if reverse:
                    reverse_out_frame = cv2.flip(img, 1, dst=None)
                    reverse_video_writer.write(reverse_out_frame)
                # eyes = eye_cascade.detectMultiScale(roi_gray, 1.1, 1, cv2.CASCADE_SCALE_IMAGE, (2, 2))
                # for (ex, ey, ew, eh) in eyes:
                #     cv2.rectangle(roi_color, (ex, ey), (ex + ew, ey + eh), (0, 255, 0), 2)
            if cv2.waitKey(1) & 0xFF == ord('q'):
                break
    if reverse:
        reverse_video_writer.release()
    face_video_writer.release()
    print('finish')
    pass


def number_of_frame(path):
    cap = cv2.VideoCapture(path)
    number = cap.get(7)
    cap.release()
    return number
